/**
 * 本地代理服务器
 * 用于解决CORS跨域问题
 * 
 * 使用方法：
 * 1. 安装依赖: npm install express cors http-proxy-middleware
 * 2. 运行: node proxy-server.js
 * 3. 在代码中使用: http://localhost:3000/proxy/api/v2/open/worksheet/getFilterRows
 */

const express = require('express');
const cors = require('cors');
const { createProxyMiddleware } = require('http-proxy-middleware');

const app = express();
const PORT = 3000;

// 启用CORS - 全局配置
app.use(cors({
  origin: '*',
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'Accept'],
  credentials: false,
  preflightContinue: false,
  optionsSuccessStatus: 200
}));

// 明确处理OPTIONS预检请求
app.options('*', cors());

// 解析JSON请求体
app.use(express.json());

// 代理中间件配置 - 简化配置避免与cors中间件冲突
const proxyOptions = {
  target: 'https://www.dachen.vip',
  changeOrigin: true,
  pathRewrite: {
    '^/proxy/': '/'
  },
  onProxyReq: (proxyReq, req, res) => {
    console.log('🚀 代理请求:', req.method, req.url, '->', proxyReq.path);
    
    // 添加必要的请求头
    proxyReq.setHeader('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36');
    proxyReq.setHeader('Accept', 'application/json, text/plain, */*');
    proxyReq.setHeader('Accept-Language', 'zh-CN,zh;q=0.9,en;q=0.8');
    
    // 如果是POST请求，确保Content-Type正确
    if (req.method === 'POST' && req.body) {
      proxyReq.setHeader('Content-Type', 'application/json');
    }
  },
  onProxyRes: (proxyRes, req, res) => {
    console.log('✅ 代理响应:', proxyRes.statusCode, req.url);
    
    // 移除可能冲突的CORS头，让cors中间件处理
    delete proxyRes.headers['access-control-allow-origin'];
    delete proxyRes.headers['access-control-allow-methods'];
    delete proxyRes.headers['access-control-allow-headers'];
  },
  onError: (err, req, res) => {
    console.error('❌ 代理错误:', err.message);
    res.status(500).json({
      error: '代理请求失败',
      message: err.message,
      url: req.url
    });
  }
};

// 代理路由
app.use('/proxy', createProxyMiddleware(proxyOptions));

// 健康检查
app.get('/health', (req, res) => {
  res.json({
    status: 'ok',
    message: '代理服务器运行正常',
    timestamp: new Date().toISOString(),
    cors: true
  });
});

// 测试路由
app.get('/test', (req, res) => {
  res.json({
    message: '代理服务器测试成功',
    cors: true,
    timestamp: new Date().toISOString()
  });
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error('❌ 服务器错误:', err);
  res.status(500).json({
    error: '服务器内部错误',
    message: err.message
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`🚀 代理服务器启动成功!`);
  console.log(`📍 地址: http://localhost:${PORT}`);
  console.log(`🔧 代理路径: /proxy/`);
  console.log(`📋 健康检查: http://localhost:${PORT}/health`);
  console.log(`🧪 测试接口: http://localhost:${PORT}/test`);
  console.log(`🌐 CORS: 已启用`);
  console.log(`📡 目标服务器: https://www.dachen.vip`);
});

module.exports = app; 